#!/usr/bin/env python
# -*- coding:utf-8 -*- #

import sys

import greenlet
from twisted.internet import reactor,protocol
from twisted.protocols import basic
from twisted.python import log

def wait_host():
    return

class RCProtocol(basic.LineReceiver):

    def connectionMade(self):
        print 'connection made'
        self.grrc=greenlet.greenlet(self.read_chunk)
        self.grrc.switch()      #切换到处理函数read_chunk()
        print 'switched to grrc'
        return

    def connectionLost(self,reason):
        print 'connection lost'
        return

    def _dataReceived(self,data):
        return

    def lineReceived(self,line):
        print 'line Received'
        self.grrc.switch(line)
        return

    def read_chunk(self):
        while True:
            #死循环中处理每次读取数据成功
            print 'in read_chunk()'
            g_self=greenlet.getcurrent()
            chunk=g_self.parent.switch()    #切换到主循环的greenlet，等被切换回来时就返回了传递的数据了
            if 'quit' in chunk.lower():
                self.transport.write('HTTP/1.1 200 OK\r\nContent-Length:10\r\n\r\nHelloWorld')
                self.transport.flush()
                self.transport.loseConnection()
                break
        return

class RCFactory(protocol.ServerFactory):
    protocol=RCProtocol

def main():
    log.startLogging(sys.stdout)
    reactor.listenTCP(8090,RCFactory())
    reactor.run()
    return

if __name__=='__main__':
    main()